package club.xiaojiawei.greedy;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 肖嘉威
 * @version 1.0
 * @date 5/29/22 10:13 PM
 * @question 763. 划分字母区间
 * @description 字符串 S 由小写字母组成。我们要把这个字符串划分为尽可能多的片段，同一字母最多出现在一个片段中。返回一个表示每个字符串片段的长度的列表。
 */
public class PartitionLabels763 {

    public static void main(String[] args) {
        PartitionLabels763 test = new PartitionLabels763();
        List<Integer> result = test.partitionLabels("ababcbacadefegdehijhklij");
        System.out.println(result);
    }

    /**ints -> System.out.println(Arrays.toString(ints))
     * 贪心
     * @param s
     * @return
     */
    public List<Integer> partitionLabels(String s) {
        int[] table = new int[128];
        char[] chars = s.toCharArray();
        int length = chars.length;
        for (int i = 0; i < length; i++) {
            table[chars[i]] = i;
        }
        ArrayList<Integer> result = new ArrayList<>();
        int left = 0;
        int right = table[chars[0]];
        for (int i = 0; i < length; i++) {
            if (i == right){
                result.add(right - left + 1);
                left = i + 1;
                if (i + 1 < length){
                    right = table[chars[i + 1]];
                }else {
                    break;
                }
            }else if (table[chars[i]] > right){
                right = table[chars[i]];
            }
        }
        return result;
    }

    /**
     * 官方-贪心
     * @param s
     * @return
     */
    public List<Integer> partitionLabels2(String s) {
        int[] last = new int[26];
        int length = s.length();
        for (int i = 0; i < length; i++) {
            last[s.charAt(i) - 'a'] = i;
        }
        List<Integer> partition = new ArrayList<Integer>();
        int start = 0, end = 0;
        for (int i = 0; i < length; i++) {
            end = Math.max(end, last[s.charAt(i) - 'a']);
            if (i == end) {
                partition.add(end - start + 1);
                start = end + 1;
            }
        }
        return partition;
    }
}
